<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.rtl.min.css" integrity="sha384-nU14brUcp6StFntEOOEBvcJm4huWjB0OcIeQ3fltAfSmuZFrkAif0T+UtNGlKKQv" crossorigin="anonymous">

    <title>Trading Platform</title>
</head>
<body>

<div class="jumbotron text-center mt-3">
    <h1>Trading Platform</h1>
</div>

<div class="container-lg">

    <div class="row mt-3">
        <div class="col-sm-3">
            <div class="card">
                <div class="card-header text-center">
                    <strong>APPLE</strong>
                </div>
                <div class="card-body">
                    <h5 class="card-title text-center" id="APPLE">$100</h5>
                    <div class="row">
                        <div class="col" align="left"><a href="#" class="btn btn-success" onclick="trade('APPLE', 'BUY')">Buy</a></div>
                        <div class="col" align="right"><a href="#" class="btn btn-warning" onclick="trade('APPLE', 'SELL')">Sell</a></div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-sm-3">
            <div class="card">
                <div class="card-header text-center">
                    <strong>AMAZON</strong>
                </div>
                <div class="card-body">
                    <h5 class="card-title text-center" id="AMAZON">$100</h5>
                    <div class="row">
                        <div class="col" align="left"><a href="#" class="btn btn-success" onclick="trade('AMAZON', 'BUY')">Buy</a></div>
                        <div class="col" align="right"><a href="#" class="btn btn-warning" onclick="trade('AMAZON', 'SELL')">Sell</a></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-3">
            <div class="card">
                <div class="card-header text-center">
                    <strong>GOOGLE</strong>
                </div>
                <div class="card-body">
                    <h5 class="card-title text-center" id="GOOGLE">$100</h5>
                    <div class="row">
                        <div class="col" align="left"><a href="#" class="btn btn-success" onclick="trade('GOOGLE', 'BUY')">Buy</a></div>
                        <div class="col" align="right"><a href="#" class="btn btn-warning" onclick="trade('GOOGLE', 'SELL')">Sell</a></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-3">
            <div class="card">
                <div class="card-header text-center">
                    <strong>MICROSOFT</strong>
                </div>
                <div class="card-body">
                    <h5 class="card-title text-center" id="MICROSOFT">$100</h5>
                    <div class="row">
                        <div class="col" align="left"><a href="#" class="btn btn-success" onclick="trade('MICROSOFT', 'BUY')">Buy</a></div>
                        <div class="col" align="right"><a href="#" class="btn btn-warning" onclick="trade('MICROSOFT', 'SELL')">Sell</a></div>
                    </div>
                </div>
            </div>
        </div>

    </div>


    <div class="row mt-3">

        <div class="col-sm-3">

            <div class="card w-100">
                <div class="card-header">
                    Profile
                </div>
                <div class="card-body">
                    <img src="" class="card-img-top" alt="...">
                    <h5 class="card-title" id="user-profile-name">.</h5>
                    <div class="row mt-3">
                        <div class="col" style="width: 60%; flex:none">
                            <strong>Available Balance</strong>
                        </div>
                        <div class="col" style="width: 40%;" id="user-available-balance">
                            $0
                        </div>
                    </div>
                    <div class="row mt-3">
                        <div class="col" style="width: 60%; flex:none">
                            <strong>Portfolio Value</strong>
                        </div>
                        <div class="col " style="width: 40%;" id="user-portfolio-value">
                            $0
                        </div>
                    </div>
                </div>
            </div>

        </div>

        <div class="col-sm-9">

            <div class="card w-100">
                <div class="card-header">
                    Portfolio
                </div>
                <div class="card-body">

                    <table class="table" id="user-portfolio">
                        <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Stock</th>
                            <th scope="col">Quantity</th>
                            <th scope="col">Current Value</th>
                        </tr>
                        </thead>
                        <tbody>
                        <!-- <tr>
                          <th scope="row">1</th>
                          <td>Mark</td>
                          <td>Otto</td>
                          <td>@mdo</td>
                        </tr>
                        <tr>
                          <th scope="row">2</th>
                          <td>Jacob</td>
                          <td>Thornton</td>
                          <td>@fat</td>
                        </tr>
                        <tr>
                          <th scope="row">2</th>
                          <td>Jacob</td>
                          <td>Thornton</td>
                          <td>@fat</td>
                        </tr> -->
                        </tbody>
                    </table>

                </div>
            </div>

        </div>
        <div id="alerts" class="mt-3">
            <!-- <div class="alert alert-danger alert-dismissible" role="alert">

            </div>
            <div class="alert alert-success alert-dismissible" role="alert">
                <div id="alert-msg"></div>
            </div> -->
            <!-- <div class="alert w-50 mp-3 alert-danger alert-dismissible position-absolute bottom-0 start-0" role="alert">
                <div id="alert-msg"></div>
            </div> -->
        </div>


    </div>

    <script>

        // get user id
        const params = new URLSearchParams(window.location.search);
        const userId = params.get('user');
        let stockPrices = {};
        let userPortfolioValue = {};
        console.log(userId);

        // elements
        const userProfileNameElement = document.getElementById('user-profile-name');
        const userPortfolioValueElement = document.getElementById('user-portfolio-value');
        const userAvailableBalanceElement = document.getElementById('user-available-balance');
        const userPortfolioContainer = document.getElementById('user-portfolio').querySelector('tbody');
        const alerts = document.getElementById('alerts');

        // get price updates
        const stockPriceUpdates = () => {
            var source = new EventSource("/stock/updates");
            source.onmessage = (evt) => {
                let event = JSON.parse(evt.data);
                let element = document.getElementById(event.ticker);
                element.innerText = `$${event.price}`;
                stockPrices[event.ticker] = event.price;
                let userQuantity = document.getElementById(`user-quantity-${event.ticker}`);
                if(userQuantity){
                    let q = parseInt(userQuantity.innerText);
                    let price = q * event.price;
                    document.getElementById(`user-value-${event.ticker}`).innerText = `$${price}`;
                    userPortfolioValue[event.ticker] = price;
                    updateUserPortfolioDisplayValue();
                }
            };
        };

        // get user information & portfolio
        const fetchUserInformation = async () => {
            const response = await fetch(`/user/${userId}`);
            const user = await response.json();
            userProfileNameElement.innerText = user.name;
            userAvailableBalanceElement.innerText = `$${user.balance}`;
            while(userPortfolioContainer.firstChild){
                userPortfolioContainer.removeChild(userPortfolioContainer.firstChild);
            }
            user.holdings.map((holding, index) => getPortfolioRow(holding, index)).forEach((holding) => userPortfolioContainer.append(holding));
            user.holdings.forEach(holding => userPortfolioValue[holding.ticker] = (holding.quantity * getStockPriceFromCache(holding.ticker)));
            userPortfolioValue['BALANCE'] = user.balance;
            console.log(userPortfolioValue);
            updateUserPortfolioDisplayValue();
        }

        const updateUserPortfolioDisplayValue = () => {
            const sum = Object.values(userPortfolioValue).reduce((acc, val) => acc + val, 0);
            if(sum >= 10000){
                userPortfolioValueElement.innerHTML = `<p class="text-success">$${sum}</p>`;
            }else{
                userPortfolioValueElement.innerHTML = `<p class="text-danger">$${sum}</p>`;
            }
        };

        const getPortfolioRow = (holding, index) => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                                <th scope="row">${index + 1}</th>
                                <td>${holding.ticker}</td>
                                <td id="user-quantity-${holding.ticker}">${holding.quantity}</td>
                                <td id="user-value-${holding.ticker}">$${holding.quantity * getStockPriceFromCache(holding.ticker) }</td>
                `;
            return tr;
        }

        const getStockPriceFromCache = (ticker) => {
            return stockPrices[ticker] ? stockPrices[ticker] : 0;
        }

        const trade = async (ticker, action) => {
            const response = await fetch('/trade', {
                method : "POST",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    userId,
                    ticker,
                    action,
                    quantity: 1
                })
            });
            if(response.ok){
                const data = await response.json();
                // we might need updated user balance & portfolio
                fetchUserInformation();
            }else{
                const data = await response.text();
                showAlert(data, 'danger');
            }

        };

        const showAlert = (msg, level) => {
            const div = document.createElement('div');
            div.innerHTML = `
                    <div class="alert alert-${level} alert-dismissible" role="alert">
                        ${msg}
                    </div>
                `;
            alerts.append(div);
            setTimeout(() => {
                div.remove();
            }, 3000);
        };

        // trigger these functions on page load
        document.addEventListener("DOMContentLoaded", () => {
            stockPriceUpdates();
            fetchUserInformation();
        });



    </script>








    <!-- <div class="row mt-3">
        <div class="col-sm-3">

            <form id="order-form" class="mt-3">
                <div class="mb-3">
                    <label class="form-label" for="customerId">Customer Id</label>
                    <input type="text" class="form-control" id="customerId">
                </div>
                <div class="mb-3">
                    <label class="form-label" for="productId">Product Id</label>
                    <input type="text" class="form-control" id="productId">
                </div>
                <div class="mb-3">
                    <label class="form-label" for="unitPrice">Price / Item</label>
                    <input type="text" class="form-control" id="unitPrice">
                </div>
                <div class="mb-3">
                        <label class="form-label" for="quantity">Quantity</label>
                        <input type="text" class="form-control" id="quantity">
                </div>
                <button type="button" id="orderBtn" class="btn btn-primary">Place Order</button>
            </form>


        </div>
        <div class="col-sm-9">

            <table class="table table-hover" id="orders">
                <thead>
                  <tr>
                    <th>Order Id</th>
                    <th>Customer Id</th>
                    <th>Product Id</th>
                    <th>Unit Price</th>
                    <th>Quantity</th>
                    <th>Total Amount</th>
                    <th>Status</th>
                  </tr>
                </thead>
                <tbody>

                </tbody>
              </table>

        </div>
    </div> -->
</div>
<!-- Optional JavaScript; choose one of the two! -->

<!-- Option 1: Bootstrap Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>

<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.min.js" integrity="sha384-BBtl+eGJRgqQAUMxJ7pMwbEyER4l1g+O15P+16Ep7Q9Q+zqX6gSbd85u4mG4QzX+" crossorigin="anonymous"></script>
-->
</body>
</html>